#include <stdlib.h>
#include <errno.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include "debug.h"
#include "rsc.h"
#include "mav_sink.h"

typedef struct mav_handle
{
    char fname[64]; /// mav file name
    FILE *fp; /// mav file HANDLE
} *MAV_HANDLE;

RSC_SINK_HANDLE mav_init_sink(const char *sink_name,int sink_type,struct rsc_sink_cfg *sink_cfg)
{
    if(sink_name==NULL)
    {
	SLOG(ERR,"sink_name is null!\n");
	return NULL;
    }
    if(sink_cfg==NULL)
    {
	SLOG(ERR,"sink_cfg is null!\n");
	return NULL;
    }
    MAV_HANDLE pmav = calloc(1,sizeof(struct mav_handle));
    if(pmav == NULL)
    {
	printf("calloc memory fail!\n");
	return NULL;
    }
    /// open file to write 
    FILE *file = fopen(sink_name,"wb");
    if(file == NULL)
    {
	printf("fopen file %s err:%s\n",sink_name,strerror(errno));
	free(pmav);
	return NULL;
    }
    strcpy(pmav->fname,sink_name);
    pmav->fp = file;

    return pmav;
}

int mav_fill_sink(RSC_SINK_HANDLE sink_handle,int subtype,struct record_frame_info *frame)
{
    if(sink_handle == NULL)
    {
	SLOG(ERR,"sink_handle is null!\n");
	return -1;
    }
    if(frame == NULL)
    {
	SLOG(ERR,"frame is null!\n");
    }
    int ret = 0;
    int type = 0;
    MAV_HANDLE pmav = (MAV_HANDLE)sink_handle;

    if(subtype == REC_DTYPE_VIDEO)
	type = 0;
    else if(subtype == REC_DTYPE_AUDIO)
	type = 1;
    else if(subtype == REC_DTYPE_META)
	type = 2;

    ret = fwrite(frame->addr,frame->len,1,pmav->fp);
    if(ret != 1)
    {
	printf("fwrite mav packet err:%s\n",strerror(errno));
	ret = RSC_EWRIT;
    }
    else
	ret = 0;

    return ret;
}

int mav_exit_sink(RSC_SINK_HANDLE sink_handle)
{
    MAV_HANDLE pmav = (MAV_HANDLE)sink_handle;
    if(pmav!=NULL)
    {
	fflush(pmav->fp);	
	fdatasync(fileno(pmav->fp));
	fclose(pmav->fp);
	free(pmav);
	pmav = NULL;
    }
    return 0;
}

